package cn.jsj.onclock.interceptor;

import cn.jsj.onclock.interceptor.swich.PassToken;
import cn.jsj.onclock.pojo.UserEnt;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Objects;

import static cn.jsj.onclock.interceptor.RequestThreadContext.cleanLocalVar;

/**
 * @author 卢斌
 */
@Slf4j
@Component
public class SecurityInterceptor implements HandlerInterceptor {

    private final RedisTemplate<String, Serializable> redisTemplate;

    private final TokenCensor tokenCensor;

    public SecurityInterceptor(RedisTemplate<String, Serializable> redisTemplate, TokenCensor tokenCensor) {
        this.redisTemplate = redisTemplate;
        this.tokenCensor = tokenCensor;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果本次请求的映射目标不是一个控制层方法，则直接通过。
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //检查是否有passToken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        // 获取用户传入的token
        String token = request.getHeader("Authorization");
        if(StringUtils.isBlank(token)){
            try {
                this.userLoginTimeOut(Objects.requireNonNull(response));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }

        // 通过用户Token，从Redis里查询该Token的密钥
        Serializable userObject = redisTemplate.opsForValue().get(token);
        if (userObject != null) {
            String sessionKey = (String) userObject;

            // 解密token获取用户个人信息
            UserEnt userEnt = tokenCensor.parseToken(token, sessionKey);

            // 用户个人信息写入到线程容器中
            RequestThreadContext.setUserEnt(userEnt);
            return true;
        }
        PrintWriter printWriter = response.getWriter();
        printWriter.write("loginAgain");
        printWriter.close();
        return false;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求结束，从线程容器中清除用户信息
        cleanLocalVar();
    }


    /**
     * 拦截器拦截到用户请求后，如果不允许用户请求访问业务逻辑层则写回给用户登录超时信息
     * @param response HttpServletResponse
     * @throws IOException 写出到用户客户端失败
     */
    private void userLoginTimeOut(HttpServletResponse response) throws IOException {
        PrintWriter printWriter = response.getWriter();
        printWriter.write("loginAgain");
        printWriter.close();
    }

    
}
